package com.mamingchao.basic.proxy.cglib_dynamic_proxy;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * cglib 底层是用asm 实现的
 * 如果 tank 类是final的，那么 cglib是不可以生成它的动态代理的，但是asm可以
 * Created by mamingchao on 2020/10/19.
 */
public class CglibProxy {

    public static void main(String[] args) {
        Enhancer  enhancer = new Enhancer();
        enhancer.setSuperclass(Tank.class);
        enhancer.setCallback(new MoveMethodInterceptor());

        Tank tank = (Tank)enhancer.create();
        tank.move();
    }
}

class MoveMethodInterceptor implements MethodInterceptor{

    private void before(){System.out.println("Start  logging....");}
    private void after(){System.out.println("End  logging....");}


    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        before();
        Object result =method.invoke(new Tank(),objects);
//        Object result = methodProxy.invoke(new Tank(),objects);
//        Object result = methodProxy.invokeSuper(o,objects);
        after();
        return result;
    }
}

class Tank{

    public void move() {
        System.out.println("Tank is moving");

        try {
            TimeUnit.SECONDS.sleep(new Random(10).nextInt());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

